<template>
  <div style="margin-top: 100px">
    <a-modal v-model:visible="visible" :title="`To ${receiverName}`" @ok="submitMsg" cancelText="取消" okText="回复" @cancel="cancelReply">
      <a-text-area v-model:value="repliedMsg" placeholder="请输入你的建议或意见......" allow-clear show-count :maxlength="300" style="height: 100px"/>
    </a-modal>
    <a-row justify="center">
      <a-col :xs="{ span: 22 }" :sm="{ span: 21 }" :md="{ span: 19 }" :lg="{ span: 14 }" :xxl="{ span: 12 }">
      <a-list :data-source="dataSource">
        <template #loadMore>
          <div
            :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }">
            <a-button @click="loadMsg" type="primary" ghost>加载更多</a-button>
          </div>
        </template>
        <template #renderItem="{ item, index }">
          <a-list-item>
            <div style="padding: 5px 0">{{ item.senderName }}&nbsp;&nbsp;{{ item.date }}</div>
            {{ item.msg }}
            <template #actions>
              <a-button @click="readMsg(item.id, index)" :disabled="item.status !== 0" type="link">已读</a-button>
              <a-button  type="link" @click="replyMsg(item.sender, item.id, item.senderName)">回复</a-button>
            </template>
            <template #extra>
              <p class="origin-msg" v-if="item.refMsg !== null">@ {{ item.refMsg }}</p>
            </template>
          </a-list-item>
        </template>
      </a-list>
      </a-col>
    </a-row>
  </div>
  <Footer />
</template>

<script lang="ts">
import { ref, defineComponent, onMounted } from 'vue'
import Footer from '@/components/Footer.vue'
import { Row, Col, List, Button, message, Modal, Input } from 'ant-design-vue'
import { addMsg, getMsg, getMsgNum, setMsgRead } from '@/service'
import { getUserName, formatDate } from '@/utils/check'
import { MessageSend } from '@/utils/ds'

interface Message {
  id: number,
  senderName: string,
  sender: number,
  msg: string,
  status: number,
  date: string,
  refMsg: string
}

export default defineComponent({
  name: 'ShowMessage',
  components: {
    ARow: Row,
    AButton: Button,
    ACol: Col,
    AList: List,
    AListItem: List.Item,
    AModal: Modal,
    ATextArea: Input.TextArea,
    Footer
  },
  setup () {
    const dataSource = ref<Message[]>([])
    const loadedCursor = ref<number>(0)
    const batchSize = ref<number>(2)
    const totalMsgNum = ref<number>(0)
    const visible = ref<boolean>(false)
    const repliedMsg = ref<string>('')
    const receiverName = ref<string>('')
    const receiverId = ref<number>(0)
    const refMsgId = ref<number>(0)

    const loadMsg = () => {
      if (loadedCursor.value >= totalMsgNum.value) {
        message.info('已加载所有消息')
        return
      }
      getMsg(loadedCursor.value, batchSize.value)
        .then(response => {
          if (response.status !== 200) {
            message.error('请求出错')
            return
          }
          const resp = response.data
          if (resp.code !== 0 || resp.data === null) {
            message.error(resp.message)
            return
          }
          const data = resp.data
          data.forEach((item: any) => {
            dataSource.value.push({
              id: item.id,
              senderName: item.senderName,
              status: item.status,
              sender: item.sender,
              msg: item.msg,
              refMsg: item.refMsg,
              date: formatDate(new Date(item.created))
            })
          })
          loadedCursor.value += batchSize.value
        })
    }

    const getMsgNumOnMounted = () => {
      getMsgNum()
        .then(response => {
          if (response.status !== 200) {
            message.error('请求出错')
            return
          }
          const resp = response.data
          if (resp.code !== 0 || resp.data === null) {
            message.error(resp.message)
            return
          }
          totalMsgNum.value = resp.data
          loadMsg()
        })
    }

    const readMsg = (id: number, idx: number) => {
      if (dataSource.value[idx].status !== 0) {
        return
      }
      setMsgRead(id)
        .then((response) => {
          if (response.status !== 200) {
            return
          }
          const resp = response.data
          if (resp.code === 0 && resp.data === true) {
            dataSource.value[idx].status = 1
          }
        })
    }

    const replyMsg = (receiverID: number, refMSGId: number, receiverName1: string) => {
      visible.value = true
      receiverId.value = receiverID
      receiverName.value = receiverName1
      refMsgId.value = refMSGId
    }

    const cancelReply = () => {
      receiverId.value = 0
      receiverName.value = 'unknown'
      visible.value = false
    }

    const submitMsg = () => {
      if (repliedMsg.value.length === 0) {
        message.info('还没有填写信息', 0.5)
        return
      }
      const sendData: MessageSend = {
        msg: repliedMsg.value,
        senderName: getUserName(),
        receiver: receiverId.value,
        ref: refMsgId.value
      }
      addMsg(sendData)
        .then((response) => {
          if (response.status !== 200) {
            message.warn('网络请求出错')
            return
          }
          const resp = response.data
          if (resp.code !== 0) {
            message.warn('服务端处理出错')
            return
          }
          if (resp.data !== null && resp.data === true) {
            message.info('提交成功')
            repliedMsg.value = ''
          }
        })
    }

    onMounted(() => {
      getMsgNumOnMounted()
    })

    return {
      dataSource,
      visible,
      repliedMsg,
      receiverId,
      receiverName,
      cancelReply,
      loadMsg,
      readMsg,
      replyMsg,
      submitMsg
    }
  }
})
</script>

<style scoped>
.origin-msg {
  text-indent: 10px;
  color: #6f6e6e;
  max-width: 800px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap
}
</style>
